package ua.pp.bizon.yandex.api.impl;

import ua.pp.bizon.yandex.api.IUserData;
import ua.pp.bizon.yandex.api.IUserDataManager;
import ua.pp.bizon.yandex.api.ObjectLookup;
import ua.pp.bizon.yandex.api.WindowManager;
import ua.pp.bizon.yandex.cache.AbstractCache;
import ua.pp.bizon.yandex.uploader.Env;

import org.apache.commons.logging.LogFactory;

public class UserDataManager extends AbstractCache implements IUserDataManager {

	public UserDataManager() {
		super("user.db");
	}

	private Env userData = null;

	public void load() {
		if (userData == null) {
			String name = props().getProperty("token");
			if (name == null || name.isEmpty()) {
				return;
			} else {
				userData = new Env("my");
				userData.setToken(name);
			}
		}
	}

	@Override
	public void save() {
		props().put("token", userData.getToken());
		super.save();
	}

	@Override
	public void relogin(String user, String token) {
		userData = new Env(user);
		userData.setToken(token);
	}

	@Override
	public IUserData get() {
		return get(true);
	}

	@Override
	public IUserData get(boolean login) {
		if (userData == null) {
			load();
		}
		if (userData == null && login) {
			ObjectLookup.lookup(WindowManager.class).login(true);
		}
		return userData;
	}

	@Override
	public void clear() {
		LogFactory.getLog(Env.class).debug("clear env");
		userData = null;
		props().remove("token");
	}

	@Override
	public void relogin(String token) {
		clear();
		userData = new Env("");
		userData.setToken(token);
	}
	
	@Override
	public void logout() {
		clear();	
	}
}
